package cn.stazxr.theme;

import javax.swing.*;
import javax.swing.plaf.ButtonUI;
import javax.swing.plaf.nimbus.NimbusLookAndFeel;
import javax.swing.tree.DefaultMutableTreeNode;
import java.awt.*;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Optional;

/**
 * Package: cn.stazxr.theme
 * 主题测试
 *
 * @Author: stazxr
 * @Create: 2023/12/15
 * @Version: v1.0
 **/
public class Test {

    static {
        try {
            UIManager.setLookAndFeel(new NimbusLookAndFeel());
        } catch (UnsupportedLookAndFeelException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        JFrame frame = new JFrame("记事本");
        frame.setBounds(500, 500, 600, 300);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setAlwaysOnTop(true);

        JTextArea area = new JTextArea();   //右边就是我们需要编辑的文本域

        File file = new File(".idea");
        DefaultMutableTreeNode root = new DefaultMutableTreeNode(file);
        File[] files = Optional.ofNullable(file.listFiles()).orElseGet(() -> new File[0]);
        for (File f : files)
            root.add(new DefaultMutableTreeNode(f.getName()));
        JTree tree = new JTree(root);   //左边就是我们的文件树
        tree.addTreeSelectionListener(e -> {   //点击文件之后，我们需要变换编辑窗口中的文本内容，这里加个监听器
            area.setText("");   //先清空
            try (FileReader reader = new FileReader(".idea/" + e.getPath().getLastPathComponent().toString())) {
                char[] chars = new char[128];   //直接开始读取内容
                int len;
                while ((len = reader.read(chars)) > 0)
                    area.setText(area.getText() + new String(chars, 0, len));   //开始写入到编辑窗口中
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        });

        JSplitPane pane = new JSplitPane();
        pane.setLeftComponent(new JScrollPane(tree));   //文件树和编辑区域都套一个滚动面板，因为有可能会撑得很大
        pane.setRightComponent(new JScrollPane(area));

        JButton button = new JButton("我是按钮");
        button.setBounds(0, 0, 200, 30);
        button.setUI(new TestJButtonUI());   //将UI设定为我们自己定义的即可
        pane.setTopComponent(button);
        frame.add(pane);
        frame.setVisible(true);

        String systemLookAndFeelClassName = UIManager.getSystemLookAndFeelClassName();
        System.out.println(systemLookAndFeelClassName);
    }
    public static class TestJButtonUI extends ButtonUI {   //继承对应的UI父类
        @Override
        public void paint(Graphics g, JComponent c) {   //我们只需要重写对应UI的paint方法就可以了
            int width = c.getWidth(), height = c.getHeight();
            g.setColor(Color.BLACK);
            g.fillRect(0, 0, width, height);
            g.setColor(Color.WHITE);
            JButton button = (JButton) c;
            g.drawString(button.getText(), 0, 20);
        }
    }
}
